import {apiHost} from './config';
import {getUserIdentityKey, getSystemInfo} from './util';
import store from '../store'
/**
 * 组装上报记录
 * @param data 上报参数
 */
export const sendTraceData = (data) => {
	let systemInfo = getSystemInfo();
    let normalData = {
        userKey: getUserIdentityKey(),
        srChn: 0,
        spChn: 0,
        srDist: 3, //接入终端类型，1：苹果APP、、2：安卓APP、3：微信、4：支付宝
		mobileSystem: systemInfo.system || '',
		mobileModels: systemInfo.model || '',
        appVersion: store.state.appVersion,
    }
    return startSendTrace(Object.assign({}, normalData, data));
}

/**
 * 上报记录
 * @param data 请求数据
 */
function startSendTrace(data) {
	http_post('/api/log/visit/record/' + data.act, data);
}

/**
 * 发起post请求
 * @param url 请求路径 必填
 * @param data 请求参数
 */
export const http_post = (url, data) => {
    return request("POST", url, data, (options, token) => {
        const append = `token=${token}`;
        if (url.indexOf("?") > -1) {
            options.url = `${options.url}&${append}`;
        } else {
            options.url = `${options.url}?${append}`;
        }

        //设置请求头
        options.header["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";
    })
};



/**
 * 发起请求
 * @param {String} method 请求方法
 * @param {String} url 连接
 * @param {any} data 数据
 * @param {Function} preRequest 前置处理函数，传递参数：options、token
 */
function request(method, url, data, preRequest) {
    //组装数据
    const options = {
        method,
        url: apiHost + url,
        data,
        header: {
            Accept: "application/json"
        }
    };
	let userInfo = uni.getStorageSync('userInfo');
	preRequest(options, userInfo.token || '');
	
    //发起请求
    return uniRequest(options).then(res => {});
}


/**
 * 网络请求基类
 * @param options 
 * @param tryCount 请求失败重试次数
 */
function uniRequest(options, tryCount = 5) {
    return new Promise((resolve, reject) => {
        const newOptions = {
            ...options,
            success: res => {
                resolve(res.data);
            },
            fail: err => {
                //失败次数小于或等于0，不再重试
                if (tryCount <= 0) {
				
                    reject(err);
                } else {
                    //重试（间隔时间以500ms为基数，逐次递增）
                    setTimeout(() => {
                        uniRequest(options, tryCount -= 1);
                    }, (6 - tryCount) * 500);
                }
            },
            complete(res) {
            }
        };

        //发起请求
		uni.request(newOptions);
    });
};